const dataURItoBlob = (dataURI, type) => {
    var binary = atob(dataURI.split(',')[1])
    var array = []
    for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i))
    }
    return new Blob([new Uint8Array(array)], { type: type })
}
/**
 * 
 * @param {string} base64 base64格式的文件
 * @param {number} size 压缩文件大小
 * @returns 压缩后base64文件
 */
export const dealImage = (base64, size = 3) => {
    return new Promise((resolve) => {
        let newImage = new Image()
        let _this = this
        let quality = 0.8 // 压缩系数0-1之间
        var blobData
        newImage.src = base64
        // newImage.setAttribute(‘crossOrigin’, ‘Anonymous’) // url为外域时需要
        let imgWidth, imgHeight
        newImage.onload = function () {
            imgWidth = this.width
            imgHeight = this.height
            let canvas = document.createElement("canvas")
            let ctx = canvas.getContext('2d')
            canvas.width = imgWidth
            canvas.height = imgHeight
            quality = 1
            ctx.clearRect(0, 0, canvas.width, canvas.height)
            ctx.drawImage(this, 0, 0, canvas.width, canvas.height)
            let base64 = canvas.toDataURL('image/png', quality) // 压缩语句
            blobData = dataURItoBlob(base64, 'image/png')

            while (blobData.size > 1024 * 1024 * size) {
                if (quality > 0) {
                    quality = quality - 0.1
                }
                imgWidth = imgWidth * quality
                imgHeight = imgHeight * quality
                canvas.width = imgWidth
                canvas.height = imgHeight
                ctx.clearRect(0, 0, imgWidth, imgHeight)
                ctx.drawImage(newImage, 0, 0, imgWidth, imgHeight)
                base64 = canvas.toDataURL('image/png', quality) // 压缩语句
                blobData = dataURItoBlob(base64, 'image/png')
            }
            if (blobData.size <= 1024 * 1024 * size) {
                console.log(quality);
                resolve(base64)
            }
        }
    })
}